//
//  YFNetworkManager+extensions.swift
//  YFSwiftWeibo
//
//  Created by tsaievan on 2017/8/28.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import AFNetworking

extension YFNetworkManager {
    func statusList(sinceId: Int64 = 0, maxId: Int64 = 0, completion:@escaping (_ status: [[String : Any]]?, _ isSuccess: Bool)->()) {
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["since_id" : "\(sinceId)", "max_id" : "\(maxId > 0 ? maxId - 1 : 0)"]
        tokenRequest(URLString: url, parameters: params) { (json, isSuccess) in
            let result = json?["statuses"] as? [[String : Any]]
            completion(result, isSuccess)
        }
    }
    
    func unreadCount(completion: @escaping (_ count: Int)->()) {
        guard let uid = tokenModel.uid else {
            return
        }
        let url = "https://api.weibo.com/2/remind/unread_count.json"
        let params = ["uid" : uid]
        tokenRequest(URLString: url, parameters: params) { (json, isSuccess) in
            let unreadCount = json?["status"] as? Int
            completion(unreadCount ?? 0)
        }
    }
}

// MARK: - 用户信息
extension YFNetworkManager {
    
    ///< 加载用户信息: https://api.weibo.com/2/users/show.json
    ///< 用户登录后立即执行
    func loadUserInfo(completion: @escaping (_ dict: [String : Any])->()) {
        guard let uid = tokenModel.uid else {
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid" : uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            ///< 完成回调
            completion((json) ?? [:])
        }
    }
}

// MARK: - OAuth相关方法
// MARK: - 加载token
extension YFNetworkManager {
        ///< 是在这个方法里面拿到token的
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id" : YFWeiboAppKey,
                      "client_secret" : YFWeiboAppSecret,
                      "grant_type" : "authorization_code",
                      "code" : code,
                      "redirect_uri" : YFRedirectURI,]
        request(method: .POST, URLString: urlString, parameters: params) { (json, isSuccess) in
            
            ///< 这个返回回来的json里面就有access_token的值
            self.tokenModel.yy_modelSet(with: json ?? [:])
            
            ///< 加载当前用户信息
            self.loadUserInfo { (json) in
                ///< 设置用户信息, screen_name 以及 avarta_large
                self.tokenModel.yy_modelSet(with: json)
                ///< 将模型做本地化存储, 其实是将模型转换成字典, 然后Json序列化之后存储到磁盘中
                self.tokenModel.saveAccount()
                print(self.tokenModel)
                completion(isSuccess)
            }
        }
    }
}
